package com.langshixiaobai.types.design.framework.tree;

import lombok.Getter;
import lombok.Setter;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

//异步策略路由
public abstract  class AbstractMultiThreadStrategyRouter<T,D,R> implements StrategyMapper<T,D,R>, StrategyHandler<T,D,R> {


    @Getter
    @Setter
    protected StrategyHandler<T, D, R> defaultStrategyHandler = StrategyHandler.DEFAULT;

    //节点路由流转
    public R router(T requestParameter, D dynamicContext) throws Exception {
        // 获取策略
        StrategyHandler<T, D, R> strategyHandler = get(requestParameter, dynamicContext);
        //
        if(strategyHandler != null) return strategyHandler.apply(requestParameter, dynamicContext);
        // 返回null 因为strategyHandler为null,无论传入什么
        return  defaultStrategyHandler.apply(requestParameter, dynamicContext);

    }
    //实施
    @Override
    public R apply(T requestParameter, D dynamicContext) throws Exception {
        // 异步加载数据
        multiThread(requestParameter, dynamicContext);
        // 业务流程受理
        return doApply(requestParameter, dynamicContext);
    }

    /**
     * 异步加载数据
     */
    public abstract void multiThread(T requestParameter, D dynamicContext) throws ExecutionException, InterruptedException, TimeoutException;

    /**
     * 业务流程受理
     */
    public abstract R doApply(T requestParameter,D dynamicContext) throws Exception;

}
